import Vue from 'vue'
// import { Message } from 'element-ui'

var store = require('store')

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// localstore
export const localstore = function(key, value) {
  if (value === void (0)) {
    var lsVal = store.get(key)
    if (lsVal && lsVal.indexOf('autostringify-') === 0) {
      return JSON.parse(lsVal.split('autostringify-')[1])
    } else {
      return lsVal
    }
  } else {
    if (typeof (value) === 'object' || Array.isArray(value)) {
      value = 'autostringify-' + JSON.stringify(value)
    }
    return store.set(key, value)
  }
}

// sessionStorage
export const session = function(key, value) {
  if (value === void (0)) {
    var lsVal = sessionStorage.getItem(key)
    if (lsVal && lsVal.indexOf('autostringify-') === 0) {
      return JSON.parse(lsVal.split('autostringify-')[1])
    } else {
      return lsVal
    }
  } else {
    if (typeof (value) === 'object' || Array.isArray(value)) {
      value = 'autostringify-' + JSON.stringify(value)
    }
    return sessionStorage.setItem(key, value)
  }
}

// 生成随机数
export const getUUID = function(len) {
  len = len || 6
  len = parseInt(len, 10)
  len = isNaN(len) ? 6 : len
  var seed = '0123456789abcdefghijklmnopqrstubwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ'
  var seedLen = seed.length - 1
  var uuid = ''
  while (len--) {
    uuid += seed[Math.round(Math.random() * seedLen)]
  }
  return uuid
}

// 深拷贝
export const deepcopy = function(source) {
  if (!source) {
    return source
  }
  const sourceCopy = source instanceof Array ? [] : {}
  for (const item in source) {
    sourceCopy[item] = typeof source[item] === 'object' ? deepcopy(source[item]) : source[item]
  }
  return sourceCopy
}

// 菜单数据组织
export const buildMenu = function(array, ckey) {
  const menuData = []
  const indexKeys = Array.isArray(array) ? array.map((e) => {
    return e.id
  }) : []
  ckey = ckey || 'parent_id'
  array.forEach(function(e, i) {
    // 一级菜单
    if (!e[ckey] || (e[ckey] === e.id)) {
      delete e[ckey]
      menuData.push(deepcopy(e)) // 深拷贝
    } else if (Array.isArray(indexKeys)) {
      // 检测ckey有效性
      const parentIndex = indexKeys.findIndex(function(id) {
        return id === e[ckey]
      })
      if (parentIndex === -1) {
        menuData.push(e)
      }
    }
  })
  const findChildren = function(parentArr) {
    if (Array.isArray(parentArr) && parentArr.length) {
      parentArr.forEach(function(parentNode) {
        array.forEach(function(node) {
          if (parentNode.id === node[ckey]) {
            if (parentNode.children) {
              parentNode.children.push(node)
            } else {
              parentNode.children = [node]
            }
          }
        })
        if (parentNode.children) {
          findChildren(parentNode.children)
        }
      })
    }
  }
  findChildren(menuData)
  return menuData
}

// 日期格式化
export const dateFormat = function(source, ignore_minute) {
  var myDate
  var separate = '-'
  var minute = ''
  if (source === void (0)) {
    source = new Date()
  }
  if (source) {
    if (source.split) {
      source = source.replace(/\-/g, '/')
    } else if (isNaN(parseInt(source))) {
      source = source.toString().replace(/\-/g, '/')
    } else {
      source = new Date(source)
    }

    if (new Date(source) && (new Date(source)).getDate) {
      myDate = new Date(source)
      if (!ignore_minute) {
        minute = (myDate.getHours() < 10 ? ' 0' : ' ') + myDate.getHours() + ':' + (myDate.getMinutes() < 10 ? '0' : '') + myDate.getMinutes()
      }
      return myDate.getFullYear() + separate + (myDate.getMonth() + 1) + separate + (myDate.getDate() < 10 ? '0' : '') + myDate.getDate() + minute
    } else {
      return source.slice(0, 16)
    }
  } else {
    return source
  }
}

// ajax错误处理
export const catchError = function(error) {
  if (error.response) {
    switch (error.response.status) {
      case 400:
        Vue.prototype.$message({
          message: error.response.data.message || '请求参数异常',
          type: 'error'
        })
        break
      case 401:
        sessionStorage.removeItem('user')
        Vue.prototype.$message({
          message: error.response.data.message || '密码错误或账号不存在！',
          type: 'warning',
          onClose: function() {
            location.reload()
          }
        })
        break
      case 403:
        Vue.prototype.$message({
          message: error.response.data.message || '无访问权限，请联系企业管理员',
          type: 'warning'
        })
        break
      default:
        Vue.prototype.$message({
          message: error.response.data.message || '服务端异常，请联系技术支持',
          type: 'error'
        })
    }
  }
  return Promise.reject(error)
}

// 得到路由
// export const getRoutes = function(array, localfile) {
//  if (!array.isArray()) {
//    return console.warn(userInfo)
//  }
//  let allowedRouter = []
//  // 转成多维数组
//  const arrayMenus = util.buildMenu(userInfo.menus)
//  // 转成hash
//  const hashMenus = {}
//  const setMenu2Hash = function(array, base) {
//    array.map(key => {
//      if (key.route) {
//        const hashKey = ((base ? base + '/' : '') + key.route).replace(/^\//, '')
//        hashMenus['/' + hashKey] = true
//        if (Array.isArray(key.children)) {
//          setMenu2Hash(key.children, key.route)
//        }
//      }
//    })
//  }
//  setMenu2Hash(arrayMenus)
//  // 遍历本地路由
//  const findLocalRoute = function(array, base) {
//    const replyResult = []
//    array.forEach(function(route) {
//      const pathKey = (base ? base + '/' : '') + route.path
//      if (hashMenus[pathKey]) {
//        if (Array.isArray(route.children)) {
//          route.children = findLocalRoute(route.children, route.path)
//        }
//        replyResult.push(route)
//      }
//    })
//    if (base) {
//      return replyResult
//    } else {
//      allowedRouter = allowedRouter.concat(replyResult)
//    }
//  }
//  const originPath = util.deepcopy(userPath[0].children)
//  findLocalRoute(originPath)
//  return allowedRouter
// }

// 得到路由
export const GetDiffRoutes = function(addRouters, visitedRouters) {
  var result = []
  var flag = false

  for (var i = 0; i < addRouters.length; i++) {
    var obj = addRouters[i]
    flag = false
    for (var j = 0; j < visitedRouters.length; j++) {
      var aj = visitedRouters[j]
      if (obj.path === aj.path) {
        flag = true
        break
      }
    }
    if (!flag) {
      result.push(obj)
    }
  }

  return result
}
// 菜单排序
export const sortMenu = function(menu) {
  if (Array.isArray(menu)) {
    var sortItem = menu.sort((a, b) => {
      if (a.orders > b.orders) {
        return 1
      }
      if (a.orders < b.orders) {
        return -1
      }
      return 0
    })
  }
  return sortItem[0].id
}

// 查找匹配的路由
export const matchPath = function(router, path) {
  let isMatched = false
  var replayResult = []
  findRoutePath(replayResult, router)
  if (Array.isArray(replayResult) && replayResult.length >= 0) {
    if (replayResult.some(v => v === path)) {
      isMatched = true
    }
  }
  return isMatched
}

function findRoutePath(replayResult, array, base) {
  array.forEach(function(route) {
    let pathKey = (base || '') + route.path
    replayResult.push(pathKey)
    if (Array.isArray(route.children)) {
      pathKey = route.path + (base || '/')
      findRoutePath(replayResult, route.children, pathKey)
    }
  })
}

